<template>
	<div class="main">
		<div class="title-div">
			<div style="height: 67%">信用城市可视化大屏</div>
			<div id="timeS" style="font-size: 0.8vw;">{{ nowTime }}</div>
		</div>
		<div class="report-div">
			<div class="report-son-1" style="width: 25%">
				<div class="report-son-2" style="height: 33%">
					<div class="report-son-title">月服务开通及使用人数</div>
					<div class="report-son-body">
						<div class="left1-buts" style="height: 25%" id="left1But">
							<div>
								<el-button class="el-button el-button--default buts"
									:class="{ active: activeService === '信用租赁' }" @click="getLeft1('信用租赁')">
									信用租赁
								</el-button>
								<el-button class="el-button el-button--default buts"
									:class="{ active: activeService === '酒店预定' }" @click="getLeft1('酒店预定')">
									酒店预定
								</el-button>
								<el-button class="el-button el-button--default buts"
									:class="{ active: activeService === '便捷泊车' }" @click="getLeft1('便捷泊车')">
									便捷泊车
								</el-button>
								<el-button class="el-button el-button--default buts"
									:class="{ active: activeService === '舒心就医' }" @click="getLeft1('舒心就医')">
									舒心就医
								</el-button>
							</div>
						</div>
						<div style="height: 75%" id="left1"></div>
					</div>
				</div>
				<div class="report-son-2" style="height: 33%">
					<div class="report-son-title">各项服务授信额度</div>
					<div class="report-son-body" id="left2"></div>
				</div>
				<div class="report-son-2" style="height: 33%">
					<div class="report-son-title">各地区信用分分布</div>
					<div class="report-son-body" id="left3"></div>
				</div>
			</div>
			<div class="report-son-1" style="width: 50%">
				<div class="mid1-1-body" style="height: 33%">
					<div class="report-son-1-1">
						<div class="report-son-1-1-body" id="mid1-1">{{ zsyNum }}</div>
						<div class="report-son-1-1-title">周使用量</div>
					</div>
					<div class="report-son-1-1">
						<div class="report-son-1-1-body" id="mid1-2">{{ syNum }}</div>
						<div class="report-son-1-1-title">总使用量</div>
					</div>
					<div class="report-son-1-1">
						<div class="report-son-1-1-body" id="mid1-3">{{ ktNum }}</div>
						<div class="report-son-1-1-title">总开通量</div>
					</div>
				</div>
				<div class="report-son-2" style="height: 66%" id="mid2"></div>
			</div>
			<div class="report-son-1" style="width: 25%">
				<div class="report-son-2" style="height: 56%">
					<div class="report-son-title">用户画像</div>
					<div class="report-son-body">
						<div class="report-son-body-1">
							<div class="report-son-body-2" id="right1-1"></div>
							<div class="report-son-body-2" id="right1-2"></div>
							<div class="report-son-body-2" id="right1-3"></div>
							<div class="report-son-body-2" id="right1-4"></div>
						</div>
					</div>
				</div>
				<div class="report-son-2" style="height: 43%">
					<div class="report-son-title">人群收入情况</div>
					<div class="report-son-body" id="right2"></div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue';
	import request from '@/utils/request'; // 确保路径正确
	import * as echarts from 'echarts'; //
	import hbsJson from './json/hbs.json';

	export default {
		setup() {
			const zsyNum = ref('');
			const syNum = ref('');
			const ktNum = ref('');
			const activeService = ref('信用租赁');
			let mid2Chart = null; // 保存 mid2 的 chart 实例
			let resizeObserver = null; // 保存 ResizeObserver 实例
			const nowTime = ref('');
			let timerInterval = null; // 定时器

			// 更新时间的函数
			const updateTime = () => {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
				const day = String(now.getDate()).padStart(2, '0');
				const hour = String(now.getHours()).padStart(2, '0');
				const minute = String(now.getMinutes()).padStart(2, '0');
				const second = String(now.getSeconds()).padStart(2, '0');

				nowTime.value = `${year}年${month}月${day}日 ${hour}:${minute}:${second}\u00A0\u00A0\u00A0\u00A0`;
			};

			const restLeft1 = (e) => {
				const chartDom = document.getElementById('left1');
				const myChart = echarts.init(chartDom);
				// 从数据中提取 groups, syNum, ktNum
				const xAxisData = e.map(item => item.groups);
				const barData = e.map(item => item.syNum);
				const lineData = e.map(item => item.ktNum);

				// 计算最大值
				const maxValue = Math.max(...barData, ...lineData);

				// 计算合适的间隔 (向上取整到接近的 50 或 100 的倍数)
				let interval = Math.ceil(maxValue / 5 / 50) * 50;

				// 如果interval太小，则调整为更合适的范围
				if (interval < 50) {
					interval = Math.ceil(maxValue / 5 / 10) * 10;
				}
				if (interval < 10) {
					interval = Math.ceil(maxValue / 5);
				}


				const option = {
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						},
					},
					grid: {
						top: '10%',
						right: '9%',
						bottom: '5%',
						left: '8%',
						containLabel: true
					},
					xAxis: [{
						type: "category",
						data: xAxisData, // 使用提取的 groups
						axisPointer: {
							type: "shadow",
						},
						axisLabel: {
							color: '#fff'
						}
					}, ],
					yAxis: [{
							type: "value",
							min: 0,
							max: Math.ceil(maxValue * 1.2 / interval) * interval, // 向上取整到最接近的间隔倍数
							interval: interval, // 使用计算后的大整数间隔
							axisLabel: {
								formatter: "{value}",
								color: '#fff'
							},

						},
						{
							type: "value",
							min: 0,
							max: Math.ceil(maxValue * 1.2 / interval) * interval, // 向上取整到最接近的间隔倍数
							interval: interval, // 使用计算后的大整数间隔
							axisLabel: {
								formatter: "{value}",
								color: '#fff'
							},
						},
					],
					series: [{
							name: "使用人数", // 对应的折线图标，根据实际业务修改
							type: "bar",
							itemStyle: {
								color: "#5087ec",
							},
							data: barData, // 使用提取的 syNum 作为柱状图数据
							yAxisIndex: 0,
						},
						{
							name: "开通人数", // 对应的折线图标，根据实际业务修改
							type: "line",
							yAxisIndex: 1,
							symbol: "circle",
							symbolSize: 4,
							itemStyle: {
								color: "#abd8dd",
							},
							data: lineData // 使用提取的 ktNum 作为折线图数据
						},
					],
				};

				myChart.setOption(option);
			};
			const restLeft2 = (e) => {
				const chartDom = document.getElementById('left2');
				const myChart = echarts.init(chartDom);
				// 从数据中提取 groups, syNum, ktNum
				const xAxisData = e.map(item => item.groups);
				const barData = e.map(item => item.num);

				const option = {
					grid: {
						left: '9%',
						right: '10%',
						bottom: '2%',
						top: '10%',
						containLabel: false,
					},
					xAxis: {
						show: false,
					},
					yAxis: [{
						type: "category",
						data: xAxisData,
						axisTick: "none",
						axisLine: "none",
						axisLabel: {
							show: true,
							color: '#D0DEEE', // 亮蓝色柱子
							align: 'top',
							verticalAlign: 'bottom',
							padding: [10, 0, 10, 10],
							fontSize: 20
						},
					}, {
						axisTick: "none",
						axisLine: "none",
						show: true,
						axisLabel: {
							fontSize: 20,
							position: 'insideRight', // 在上方显示
							color: '#D0DEEE',
							align: 'top',
							verticalAlign: 'bottom',
							padding: [0, 0, 10, -50],
						},
						data: barData,
					}],
					series: [{
						name: 'value',
						type: 'bar',
						zlevel: 1,
						showBackground: true,
						backgroundStyle: {
							opacity: 0.098,
							color: '#FFFFFF', // 亮蓝色柱子
							borderRadius: 20 // 右侧圆角
						},
						itemStyle: {
							color: '#36A5FF', // 亮蓝色柱子
							borderRadius: 20 // 右侧圆角
						},
						barWidth: '20%',
						data: barData,
					}],
				}
				myChart.setOption(option);
			};
			const restLeft3 = (e) => {
				const chartDom = document.getElementById('left3');
				const myChart = echarts.init(chartDom);
				const xAxisData = e.map(item => item.groups);
				const seriesData = e.map(item => ({
					name: item.groups,
					value: item.num
				})); // 构造 series.data

				const option = {
					color: ['#3398DB'],
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow',
							z: 0
						},
						formatter: function(params) {
							return params[0].name + ': ' + params[0].value; // 修改提示框显示
						},
						showContent: true // 显示提示框内容
					},
					dataZoom: {
						show: true,
						type: 'slider',
						realtime: true,
						height: 10,
						start: 0,
						end: 80,
						textStyle: false,
					},
					xAxis: [{
						type: 'category',
						axisTick: {
							show: false,
							alignWithLabel: true
						},
						axisLabel: {
							color: '#fff',
							interval: 0
						},
						axisLine: {
							lineStyle: {
								color: '#2b386a',
								fontSize: 16
							}
						},
						data: xAxisData // 使用提取的 groups
					}],
					yAxis: [{
						type: 'value',
						boundaryGap: ['0%', '10%'],
						splitLine: {
							show: false
						},
						axisLabel: {
							color: '#fff',
							fontSize: 16
						},
						axisLine: {
							lineStyle: {
								color: '#2b386a'
							}
						}
					}],
					series: [{
						name: '区域数据',
						type: 'bar',
						barWidth: 26,
						emphasis: {
							label: {
								show: true,
								position: 'top',
								distance: 8,
								textStyle: {
									color: '#fff',
									fontSize: 18
								}
							}
						},
						itemStyle: {
							normal: {
								show: true,
								color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
										offset: 0,
										color: '#07fb96'
									},
									{
										offset: 1,
										color: '#3149fc'
									}
								])
							}
						},
						data: seriesData // 使用构造后的 seriesData
					}]
				}
				myChart.setOption(option);
			};
			const restMid1 = (e) => {
				zsyNum.value = e.zsyNum;
				syNum.value = e.syNum;
				ktNum.value = e.ktNum;
			};
			const restMid2 = (e) => {
				const chartDom = document.getElementById('mid2');

				// 检查是否已经初始化
				if (mid2Chart) {
					mid2Chart.dispose(); // 销毁之前的实例
				}

				mid2Chart = echarts.init(chartDom);

				echarts.registerMap('hubei', hbsJson);

				// 从传入的 e 值中提取数据
				const data = e.map(item => ({
					name: item.groups,
					value: item.num
				}));

				// 计算数据的最大值，用于 visualMap
				const maxValue = Math.max(...data.map(item => item.value));

				const option = {
					tooltip: {
						formatter: '{b}: {c}' // 显示地名和数值
					},
					visualMap: {
						min: 0,
						max: maxValue,
						show: false, // 隐藏visualMap组件
						inRange: {
							color: ['#ffeeee', '#ffcccc', '#ff9999', '#ff6666', '#ff3333', '#ff0000']
						}
					},
					series: [{
						name: '地图数据',
						type: 'map',
						zoom: 1.1,
						roam: true,
						mapType: 'hubei', // 替换为 hebei, 必须和geojson文件对应
						itemStyle: {
							normal: {
								borderColor: 'brown',
								areaColor: '#091e5d', // 区块默认透明
								borderWidth: 1,
								borderColor: '#ffcccc'
							},
							emphasis: {
								areaColor: '#ffcccc', // 鼠标悬停时的颜色
								label: {
									show: true,
									textStyle: {
										color: 'darkslategray',
									},
								}
							}
						},
						data: data, // 使用传入的数据
						label: {
							normal: {
								show: true,
								textStyle: {
									fontSize: 10,
									color: '#fff'
								}
							},
							emphasis: {
								textStyle: {
									color: '#fff'
								}
							}
						}
					}]
				};

				mid2Chart.setOption(option);
				// 使用 ResizeObserver 监听容器大小变化
				resizeObserver = new ResizeObserver(() => {
					mid2Chart.resize();
				});
				resizeObserver.observe(chartDom);
			};
			const restRight11 = (e) => {
				const chartDom = document.getElementById('right1-1');
				const myChart = echarts.init(chartDom);
				var data = e.map(item => ({
					name: item.groups,
					value: item.num
				}));
				var colorScheme1 = ['#3daff6', '#4dc794', '#f76e6d', '#ffb980', '#8c9eff'];
				const option = {
					tooltip: {
						trigger: "item",
						formatter: "{b}: {c} ({d}%)"
					},
					color: colorScheme1,
					series: [{
						name: "地区数据",
						type: "pie",
						radius: ["60%", "90%"],
						avoidLabelOverlap: false,
						roseType: 'radius',
						label: {
							show: true,
							position: "center",
							fontSize: 16,
							fontWeight: "bold",
							formatter: function() {
								return `{total|信用分占比}`;
							},
							rich: {
								total: {
									fontSize: 22,
									fontWeight: "bold",
									color: "#fff",
								},
							},
						},
						labelLine: {
							show: false
						},
						data: data,
					}, ],
				};
				myChart.setOption(option);
			};
			const restRight12 = (e) => {
				const chartDom = document.getElementById('right1-2');
				const myChart = echarts.init(chartDom);
				var data = e.map(item => ({
					name: item.groups,
					value: item.num
				}));
				var colorScheme1 = ['#ff7f50', '#87cefa', '#da70d6', '#32cd32', '#6495ed'];
				const option = {
					tooltip: {
						trigger: "item",
						formatter: "{b}: {c} ({d}%)"
					},
					color: colorScheme1,
					series: [{
						name: "地区数据",
						type: "pie",
						radius: ["60%", "90%"],
						avoidLabelOverlap: false,
						roseType: 'radius',
						label: {
							show: true,
							position: "center",
							fontSize: 16,
							fontWeight: "bold",
							formatter: function() {
								return `{total|年龄分布}`;
							},
							rich: {
								total: {
									fontSize: 22,
									fontWeight: "bold",
									color: "#fff",
								},
							},
						},
						labelLine: {
							show: false
						},
						data: data,
					}, ],
				};
				myChart.setOption(option);
			};
			const restRight13 = (e) => {
				const chartDom = document.getElementById('right1-3');
				const myChart = echarts.init(chartDom);
				var data = e.map(item => ({
					name: item.groups,
					value: item.num
				}));
				var colorScheme1 = ['#dda0dd', '#90ee90', '#a0522d', '#d2691e', '#ff69b4'];
				const option = {
					tooltip: {
						trigger: "item",
						formatter: "{b}: {c} ({d}%)"
					},
					color: colorScheme1,
					series: [{
						name: "地区数据",
						type: "pie",
						radius: ["60%", "90%"],
						avoidLabelOverlap: false,
						roseType: 'radius',
						label: {
							show: true,
							position: "center",
							fontSize: 16,
							fontWeight: "bold",
							formatter: function() {
								return `{total|性别分布}`;
							},
							rich: {
								total: {
									fontSize: 22,
									fontWeight: "bold",
									color: "#fff",
								},
							},
						},
						labelLine: {
							show: false
						},
						data: data,
					}, ],
				};
				myChart.setOption(option);
			};
			const restRight14 = (e) => {
				const chartDom = document.getElementById('right1-4');
				const myChart = echarts.init(chartDom);
				var data = e.map(item => ({
					name: item.groups,
					value: item.num
				}));
				var colorScheme1 = ['#e0ffff', '#bc8f8f', '#7fffd4', '#ffdab9', '#cd5c5c'];
				const option = {
					tooltip: {
						trigger: "item",
						formatter: "{b}: {c} ({d}%)"
					},
					color: colorScheme1,
					series: [{
						name: "地区数据",
						type: "pie",
						radius: ["60%", "90%"],
						avoidLabelOverlap: false,
						roseType: 'radius',
						label: {
							show: true,
							position: "center",
							fontSize: 16,
							fontWeight: "bold",
							formatter: function() {
								return `{total|工作类型分布}`;
							},
							rich: {
								total: {
									fontSize: 22,
									fontWeight: "bold",
									color: "#fff",
								},
							},
						},
						labelLine: {
							show: false
						},
						data: data,
					}, ],
				};
				myChart.setOption(option);
			};
			const restRight2 = (e) => {
				const chartDom = document.getElementById('right2');
				const myChart = echarts.init(chartDom);

				// 数据 - 从e值动态生成data， 包含color
				const data = e.map((item, index) => ({
					name: item.groups,
					value: item.num,
					//  随机生成颜色
					color: '#' + Math.floor(Math.random() * 16777215).toString(16)
				}));

				const option = {
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						}
					},
					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						top: '25%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						data: data.map(item => item.name),
						axisLabel: {
							color: '#fff'
						},
						axisLine: {
							lineStyle: {
								color: '#fff'
							}
						},
						axisTick: {
							alignWithLabel: true,
							lineStyle: {
								color: '#fff'
							}
						}
					},
					yAxis: {
						type: 'value',
						axisLabel: {
							color: '#fff'
						},
						axisLine: {
							lineStyle: {
								color: '#fff'
							}
						},
						splitLine: {
							lineStyle: {
								color: 'rgba(255,255,255,0.2)'
							}
						}
					},
					series: [{
						type: 'bar',
						barWidth: '60%',
						data: data.map(item => ({
							value: item.value,
							itemStyle: {
								color: item.color
							}
						})),
						label: {
							show: true,
							position: 'top',
							color: '#fff',
							formatter: '{c}'
						}
					}],
				};
				myChart.setOption(option);
			};
			const getLeft1 = async (serviceType) => {
				activeService.value = serviceType;
				try {
					getReportData(`/rpt/left1?serverType=${serviceType}`, restLeft1); // 直接传递处理函数
				} catch (error) {
					console.error("Error fetching left2 data:", error);
				}
			};
			const getReportData = (url, handler) => {
				request({
						url: url,
						method: 'get',
					})
					.then(response => {
						handler(response); // 直接调用处理函数
					})
					.catch(error => {
						console.error("Request failed:", error);
					});
			};

			onMounted(() => {
				// 初始化时间
				updateTime();
				timerInterval = setInterval(updateTime, 1000);
				getReportData('/rpt/left1?serverType=信用租赁', restLeft1);
				getReportData('/rpt/left2', restLeft2);
				getReportData('/rpt/left3', restLeft3);
				getReportData('/rpt/mid1', restMid1);
				getReportData('/rpt/mid2', restMid2);
				getReportData('/rpt/right11', restRight11);
				getReportData('/rpt/right12', restRight12);
				getReportData('/rpt/right13', restRight13);
				getReportData('/rpt/right14', restRight14);
				getReportData('/rpt/right2', restRight2);
			
			});

			onUnmounted(() => {
				// 组件卸载时，销毁图表实例和取消监听
				if (mid2Chart) {
					mid2Chart.dispose();
				}
				if (resizeObserver) {
					resizeObserver.disconnect()
				}
				// 清除定时器
				clearInterval(timerInterval);
			});

			return {
				activeService,
				zsyNum,
				syNum,
				ktNum,
				getLeft1,
				nowTime,
			};
		},
	};
</script>

<style scoped>
	@import './css/style.css';
</style>